package com.jeff.android.lab.jetpack.work

import android.os.Bundle
import android.widget.Button
import androidx.lifecycle.observe
import androidx.work.*
import butterknife.BindView
import butterknife.OnClick
import com.jeff.android.lab.BaseFragment
import com.jeff.android.lab.R
import com.jeff.utils.LogUtil
import java.util.concurrent.TimeUnit
import androidx.work.OneTimeWorkRequestBuilder as OneTimeWorkRequestBuilder1

/**
 * @author: dingfeng
 * @date: 2020-10-29
 * @since: 1.0.0
 */
class WorkerFragment : BaseFragment() {

    @BindView(R.id.btn_exec)
    lateinit var btn_exec: Button

    override fun getRootLayout(): Int {
        return R.layout.jetpack_worker_fragment
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun initView() {

    }

    @OnClick((R.id.btn_exec))
    fun onExec() {
        val requestA = OneTimeWorkRequestBuilder1<WorkerA>().build()
        val requestB = OneTimeWorkRequestBuilder1<WorkerB>().build()


        val builder = Data.Builder()
        builder.putString("data", "Hello Worker")
        val request = OneTimeWorkRequestBuilder1<WorkerTask>().setInputData(builder.build()).setInitialDelay(5, TimeUnit.SECONDS).build()
        WorkManager.getInstance(mContext).beginWith(listOf(requestA, requestB)).then(request).enqueue()


        val periodRequestB = PeriodicWorkRequestBuilder<WorkerB>(15, TimeUnit.MINUTES).build()
        WorkManager.getInstance(mContext).enqueue(periodRequestB)


        WorkManager.getInstance(mContext).enqueueUniqueWork("work-b", ExistingWorkPolicy.REPLACE, requestB)
        val workInfo = WorkManager.getInstance(mContext).getWorkInfosByTag("work-b")


//        WorkManager.getInstance(mContext).getWorkInfoByIdLiveData(requestB.id)
//                .observe(viewLifecycleOwner) { workInfo ->
//                    if(workInfo?.state == WorkInfo.State.SUCCEEDED) {
//                        LogUtil.d("dingfeng", "WorkerB result:" + workInfo.outputData.getString("data"))
//                    }
//                }


//
//        // 使用约束
//        val constraints = Constraints.Builder()
//                .setRequiredNetworkType(NetworkType.CONNECTED)
//                .build()
//        val requestC = OneTimeWorkRequestBuilder1<WorkerTask>().setConstraints(constraints).setInitialDelay(15, TimeUnit.SECONDS).build()
//        WorkManager.getInstance(mContext).enqueue(requestC)
    }

    override fun initData() {


    }

}
